package com.yunji.common.base;

import com.baomidou.mybatisplus.annotation.TableField;
import com.google.common.base.Joiner;
import com.yunji.common.framework.MybatisPlusHelper;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author : peter-zhu
 * @date : 2024/10/22 09:38
 * @description : TODO
 **/
@Data
@NoArgsConstructor
public class PageDTO {
    @ApiModelProperty("页码")
    //@NotNull(message = "页码不能为空")
    @TableField(exist = false)
    private Integer pageNum = 1;

    @ApiModelProperty("数量")
    //@NotNull(message = "数量不能为空")
    @TableField(exist = false)
    private Integer pageSize = 10;

    @ApiModelProperty(hidden = true)
    @TableField(exist = false)
    private long total;

    @ApiModelProperty("是否分页 false就是分页 true是不分页")
    @TableField(exist = false)
    private boolean export;

    @ApiModelProperty("排序字段 json可以传数组 尽量用post json (form表单没法传数组 必须以,字符串隔开 世界上任何form表单请求都没法数组 就算传了数组也是有机制把它变成了逗号隔开)")
    @TableField(exist = false)
    private Set<String> orderFields;

    @ApiModelProperty("降序填true 升序false 不传默认升序")
    @TableField(exist = false)
    private boolean orderDesc;

//    public static void main(String[] args) {
//        List<String> list = Lists.newArrayList("orderSumAmt","orderHbAmt","orderAvgAmt");
//        List<String> collect = list.stream().map(MybatisPlusHelper::camelToSnake).collect(Collectors.toList());
//        String join = Joiner.on(",").join(collect);
//        System.out.println(join);
//    }


    /**
     * @author : peter-zhu
     * @date : 2025/1/6 9:51
     * @description : 这里是返回要排序的字段 逗号拼接 但是帮忙拼接 order by fields desc
     */
    //FIXME  暂时这样 但是会有sql注入风险
    public String getOrderFieldSql() {
        Set<String> of = getOrderFields();
        if (of != null && !of.isEmpty()) {
            List<String> collect = of.stream().map(MybatisPlusHelper::camelToSnake).collect(Collectors.toList());
            return Joiner.on(",").join(collect);
        }
        return null;
    }

    /**
     * @author : peter-zhu
     * @date : 2025/1/6 9:51
     * @description : 帮忙拼接 order by fields desc
     */
    public String getOrderSql() {
        String orderFieldSql = getOrderFieldSql();
        if (orderFields != null && !orderFields.isEmpty()) {
            return " order by " + orderFieldSql + (orderDesc ? " desc" : "");
        }
        return "";
    }

    public PageDTO(Integer pageNum, Integer pageSize) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
    }

    public Integer getPageNum() {
        if (isExport()) {
            return 1;
        }
        return pageNum;
    }

    public Integer getPageSize() {
        if (isExport()) {
            return Integer.MAX_VALUE;
        }
        return pageSize;
    }
}
